package com.jayanslow.lighting.server.clients;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;

import com.jayanslow.lighting.server.parser.Command;

public class ClientManager {
	public static final int MAX_CLIENTS = 256;
	public static final int MAX_COMMANDS = 60;
	public static final String DEFAULT_NAME = "unknown";
	
	private volatile short currId = 0;
	private volatile ArrayBlockingQueue<Client> clients;
	private volatile ArrayBlockingQueue<Command> cmds;
	
	public ClientManager() {
		clients = new ArrayBlockingQueue<Client>(MAX_CLIENTS);
		cmds = new ArrayBlockingQueue<Command>(MAX_COMMANDS);
	}
	public void addClient(Socket socket) {
		Client c = new Client(this, socket);
		System.out.println("CLIENT CONNECT " + c.getIp() + " AS " + c.getDeviceName());
		clients.add(c);
		c.start();
	}
	public void removeClient(Client client) {
		if (!clients.contains(client)) return;
		System.out.println("CLIENT DISCONNECT " + client.getDeviceName());		
		clients.remove(client);
	}
	public void addCommand(Client client, String cmd) {
		Command command = new Command(client, cmd);
		System.out.println("CLIENT COMMAND " + client.getDeviceName() + " : " + cmd);
		cmds.add(command);
	}
	public boolean hasCommand() {
		return !cmds.isEmpty();
	}
	public Command getCommand() {
		if (!hasCommand()) return null;
		try {
			return cmds.take();
		} catch (InterruptedException e) { }
		return null;
	}
	public short getNextId() {
		return (short) (currId + 1);
	}
	public void moveNextId() {
		currId += 1;
	}
}
